package com.css.fxfzypg.modules.rating.task.dao;

import com.css.fxfzypg.modules.rating.task.model.entity.KpRatingTaskProgress;
import com.css.fxfzypg.util.PlatformObjectUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class KpRatingTaskProgressRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void insert(KpRatingTaskProgress kpRatingTaskProgress) {
        String sql = "INSERT INTO kp_rating_task_progress(id, krt_id, status, status_time) values(:id, :krtId, :status, :statusTime)";
        namedParameterJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(kpRatingTaskProgress));
    }

    public List<KpRatingTaskProgress> list(KpRatingTaskProgress kpRatingTaskProgress) {
        StringBuilder sql = new StringBuilder("select * from kp_rating_task_progress where 1=1 ");
        if (ObjectUtils.isNotEmpty(kpRatingTaskProgress.getId())) {
            sql.append(" and id = '").append(kpRatingTaskProgress.getId()).append("' ");
        }
        if (ObjectUtils.isNotEmpty(kpRatingTaskProgress.getKrtId())) {
            sql.append(" and krt_id = '").append(kpRatingTaskProgress.getKrtId()).append("' ");
        }
        if (ObjectUtils.isNotEmpty(kpRatingTaskProgress.getStatus())) {
            sql.append(" and status = '").append(kpRatingTaskProgress.getStatus()).append("' ");
        }
        if (ObjectUtils.isNotEmpty(kpRatingTaskProgress.getStatusTime())) {
            sql.append(" and status_time = '").append(kpRatingTaskProgress.getStatusTime()).append("' ");
        }
        sql.append(" order by status_time desc");
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(KpRatingTaskProgress.class));
    }

    public KpRatingTaskProgress getByKrtIdAndStatus(String krtId, int status) {
        try {
            List<KpRatingTaskProgress> list = jdbcTemplate.query("select * from kp_rating_task_progress where krt_id = '" + krtId + "' and status =  '" + status + "'", new BeanPropertyRowMapper<>(KpRatingTaskProgress.class));
            if (PlatformObjectUtils.isNotEmpty(list)){
                return list.get(0);
            }else {
                return null;
            }
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
}
